package newsSystem.Test;

import newsSystem.utils.DBUtil;

import javax.swing.*;
import java.awt.*;
import java.sql.*;

public class ImageTest extends JFrame {
    private JLabel imageLabel;

    public static void main(String[] args) {
        new  ImageTest();
    }
    public ImageTest() {
        setTitle("图片测试");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);

        // 创建用于显示图像的标签
        imageLabel = new JLabel();
        add(imageLabel, BorderLayout.CENTER);

        // 从数据库中加载图像并显示
        loadImage();

        setVisible(true);
    }

    public void loadImage() {
        Connection connection = null;
        ResultSet resultSet = null;
        PreparedStatement statement = null;
        try {
            // 连接数据库
            connection = DBUtil.getConnection();
            statement = connection.prepareStatement("SELECT NewsImage FROM newsinfo WHERE NewsID = 2");
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                // 从结果集中获取图像数据
                byte[] imageData = resultSet.getBytes("NewsImage");

                // 将二进制数据转换为图像
                ImageIcon imageIcon = new ImageIcon(imageData);
//                Image image = imageIcon.getImage();
//                System.out.println(image);
                // 将图像显示在标签中
                imageLabel.setIcon(imageIcon);
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            DBUtil.closeResultSet(resultSet);
            DBUtil.closePreparedStatement(statement);
            DBUtil.closeConnection(connection);
        }
    }
}

